package com.hyfrogx.modules.zoom.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hyfrogx.common.exception.MyException;
import com.hyfrogx.config.ZoomConfig;
import com.hyfrogx.modules.zoom.dao.HyZoomUserDao;
import com.hyfrogx.modules.zoom.entity.HyZoomMeeting;
import com.hyfrogx.modules.zoom.entity.HyZoomUser;
import com.hyfrogx.modules.zoom.entity.HyZoomVipUserEntity;
import com.hyfrogx.modules.zoom.service.HyZoomMeetingService;
import com.hyfrogx.modules.zoom.service.HyZoomUserService;
import com.hyfrogx.modules.zoom.service.HyZoomVipUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @author ：Li9527
 * @date ：Created in 2019-03-29 13:17
 * @description：Zoom账号交互api业务ServiceImpl
 * @modified By：
 * @version: 1.0
 */
@Service("HyZoomUserService")
@Slf4j
public class HyZoomUserServiceImpl implements HyZoomUserService {

    @Autowired
    HyZoomUserDao hyZoomUserDao;

    @Autowired
    ZoomConfig zoomConfig;

    @Autowired
    HyZoomVipUserService zoomVipUserService;

    @Autowired
    @Lazy
    HyZoomMeetingService meetingService;

    @Override
    public String creatZoomUser(Long uid, Integer meeting_capacity) {
        HyZoomUser hyUserZoom = new HyZoomUser();
        //定义邮箱规则
        String random = UUID.randomUUID().toString();
        String email = random.substring(0, 5) + "Num" + meeting_capacity + "@heyoo-vr.com";
        //such----54321capacity25@heyoo-vr.com
        //接入参数
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("api_key", zoomConfig.getApi_key()));
        params.add(new BasicNameValuePair("api_secret", zoomConfig.getApi_secret()));
        params.add(new BasicNameValuePair("email", email));
        params.add(new BasicNameValuePair("password", "123456"));
        params.add(new BasicNameValuePair("meeting_capacity", meeting_capacity.toString()));
        params.add(new BasicNameValuePair("type", "3"));
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost post = new HttpPost("https://www.zoomus.cn/v1/user/autocreate2");
        CloseableHttpResponse response = null;
        try {
            // 加浏览器头防止被过滤
            post.setHeader("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT5.1; en-US; rv:0.9.4)");
            post.setEntity(new UrlEncodedFormEntity(params, "utf-8"));
            response = httpclient.execute(post);
            JSONObject json;
            if (response.getStatusLine().getStatusCode() == 200) {
                HttpEntity httpEntity = response.getEntity();
                if (null != httpEntity) {
                    String retSrc = EntityUtils.toString(httpEntity);
                    json = new JSONObject(retSrc);
                    hyUserZoom.setUid(uid);
                    hyUserZoom.setZoomuserid(json.getString("id"));
                    hyUserZoom.setType(json.getInt("type"));
                    hyUserZoom.setToken(getusertoken(json.getString("id")));
                    int flag = hyZoomUserDao.insert(hyUserZoom);
                    //数据持久化成功
                    if (flag > 0) {
                        return json.getString("id");
                    } else {
                        return "0";
                    }
                }
            }
        } catch (Exception e) {
            throw new MyException(e.getMessage());
        }
        return "0";
    }

    @Override
    public String getusertoken(String hostid) {
        String result = "";
        //接入参数
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("api_key", zoomConfig.getApi_key()));
        params.add(new BasicNameValuePair("api_secret", zoomConfig.getApi_secret()));
        params.add(new BasicNameValuePair("id", hostid));
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost post = new HttpPost("https://www.zoomus.cn/v1/user/get");
        CloseableHttpResponse response = null;
        try {
            // 加浏览器头防止被过滤
            post.setHeader("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT5.1; en-US; rv:0.9.4)");
            post.setEntity(new UrlEncodedFormEntity(params, "utf-8"));
            response = httpclient.execute(post);
            if (response.getStatusLine().getStatusCode() == 200) {
                HttpEntity httpEntity = response.getEntity();
                if (null != httpEntity) {
                    String retSrc = EntityUtils.toString(httpEntity);
                    JSONObject json = new JSONObject(retSrc);
                    String token = json.getString("token");
                    return token;
                }
            }
        } catch (Exception e) {
            throw new MyException(e.getMessage());
        }
        return result;
    }

    @Override
    public String getuserZak(String hostid) {
        String result = "";
        //接入参数
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("api_key", zoomConfig.getApi_key()));
        params.add(new BasicNameValuePair("api_secret", zoomConfig.getApi_secret()));
        params.add(new BasicNameValuePair("id", hostid));
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost post = new HttpPost("https://www.zoomus.cn/v1/user/get");
        CloseableHttpResponse response = null;
        try {
            // 加浏览器头防止被过滤
            post.setHeader("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT5.1; en-US; rv:0.9.4)");
            post.setEntity(new UrlEncodedFormEntity(params, "utf-8"));
            response = httpclient.execute(post);
            if (response.getStatusLine().getStatusCode() == 200) {
                HttpEntity httpEntity = response.getEntity();
                if (null != httpEntity) {
                    String retSrc = EntityUtils.toString(httpEntity);
                    JSONObject json = new JSONObject(retSrc);
                    String zak = json.getString("zak");
                    return zak;
                }
            }
        } catch (Exception e) {
            throw new MyException(e.getMessage());
        }
        return result;
    }

    @Override
    public Integer deleteZoomUser(String hostid) {
        //接入参数
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("api_key", zoomConfig.getApi_key()));
        params.add(new BasicNameValuePair("api_secret", zoomConfig.getApi_secret()));
        params.add(new BasicNameValuePair("id", hostid));
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost post = new HttpPost("https://www.zoomus.cn/v1/user/delete");
        CloseableHttpResponse response = null;
        try {
            // 加浏览器头防止被过滤
            post.setHeader("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT5.1; en-US; rv:0.9.4)");
            post.setEntity(new UrlEncodedFormEntity(params, "utf-8"));
            response = httpclient.execute(post);
            if (response.getStatusLine().getStatusCode() == 200) {
                HttpEntity httpEntity = response.getEntity();
                if (null != httpEntity) {
                    String retSrc = EntityUtils.toString(httpEntity);
                    JSONObject json;
                    json = new JSONObject(retSrc);
                    // 同时删除本地账号
                    hyZoomUserDao.delete(new QueryWrapper<HyZoomUser>().eq("zoomUserId", hostid));
                    // 查出该账号对应会议室,删除会议室
                    HyZoomMeeting zoomMeeting = meetingService.getOne(new QueryWrapper<HyZoomMeeting>().eq("hostId", hostid));
                    // 删除会议室
                    meetingService.removeById(zoomMeeting.getId());
                    // 删除一对多关系表
                    zoomVipUserService.remove(new QueryWrapper<HyZoomVipUserEntity>().eq("zid", zoomMeeting.getId()));
                    return 1;
                }
            }
        } catch (Exception e) {
            throw new MyException(e.getMessage());
        }
        return 0;
    }

    @Override
    public Integer getUserMeetingCapacity(String hostid) {
        //接入参数
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("api_key", zoomConfig.getApi_key()));
        params.add(new BasicNameValuePair("api_secret", zoomConfig.getApi_secret()));
        params.add(new BasicNameValuePair("id", hostid));
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost post = new HttpPost("https://www.zoomus.cn/v1/user/get");
        CloseableHttpResponse response = null;
        try {
            // 加浏览器头防止被过滤
            post.setHeader("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT5.1; en-US; rv:0.9.4)");
            post.setEntity(new UrlEncodedFormEntity(params, "utf-8"));
            response = httpclient.execute(post);
            if (response.getStatusLine().getStatusCode() == 200) {
                HttpEntity httpEntity = response.getEntity();
                if (null != httpEntity) {
                    String retSrc = EntityUtils.toString(httpEntity);
                    JSONObject json = new JSONObject(retSrc);
                    Integer meetingCapacity = json.getInt("meeting_capacity");
                    return meetingCapacity;
                }
            }
        } catch (Exception e) {
            throw new MyException(e.getMessage());
        }
        return null;
    }

    @Override
    public String getUserList() {
        // java获取utc时间
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeZone(TimeZone.getTimeZone("GMT"));
        // 接入参数
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("api_key", zoomConfig.getApi_key()));
        params.add(new BasicNameValuePair("api_secret", zoomConfig.getApi_secret()));
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost post = new HttpPost("https://www.zoomus.cn/v1/user/list");
        CloseableHttpResponse response = null;
        try {
            // 加浏览器头防止被过滤
            post.setHeader("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT5.1; en-US; rv:0.9.4)");
            post.setEntity(new UrlEncodedFormEntity(params, "utf-8"));
            response = httpclient.execute(post);
            if (response.getStatusLine().getStatusCode() == 200) {
                HttpEntity httpEntity = response.getEntity();
                if (null != httpEntity) {
                    String retSrc = EntityUtils.toString(httpEntity);
                    JSONObject json = new JSONObject(retSrc);
                    return json.toString();
                }
            }
        } catch (Exception e) {
            throw new MyException(e.getMessage());
        }
        return "0";
    }

    @Override
    public Integer updateUser(String hostid, Integer meeting_capacity) {
        // 接入参数
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("api_key", zoomConfig.getApi_key()));
        params.add(new BasicNameValuePair("api_secret", zoomConfig.getApi_secret()));
        params.add(new BasicNameValuePair("id", hostid));
        params.add(new BasicNameValuePair("meeting_capacity", meeting_capacity.toString()));
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost post = new HttpPost("https://www.zoomus.cn/v1/user/update");
        CloseableHttpResponse response = null;
        try {
            // 加浏览器头防止被过滤
            post.setHeader("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT5.1; en-US; rv:0.9.4)");
            post.setEntity(new UrlEncodedFormEntity(params, "utf-8"));
            response = httpclient.execute(post);
            if (response.getStatusLine().getStatusCode() == 200) {
                HttpEntity httpEntity = response.getEntity();
                if (null != httpEntity) {
                    String retSrc = EntityUtils.toString(httpEntity);
                    JSONObject json = new JSONObject(retSrc);
                    return 1;
                }
            }
        } catch (Exception e) {
            throw new MyException(e.getMessage());
        }
        return null;
    }

}
